package com.example.customclassloader;

import org.springframework.stereotype.Component;

import java.net.URL;
import java.net.URLClassLoader;

/**
 * 从URLClassLoader派生，定义一个名为ChildFirstClassLoader的类加载器，用于加载被托管的jar
 * @author xionglei
 * @version 1.0.0
 * 2021年08月18日 16:58
 */
public class ChildFirstClassLoader extends URLClassLoader {

    protected ChildFirstClassLoader(URL[] urls, ClassLoader parentLoader) {
        super(urls, parentLoader);
    }

    @Override
    public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            // 添加自定义加载Class类对象,先自己加载
            if (c == null && !name.startsWith("java.")) {
                c = this.findClass(name);
            }
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (getParent() != null) {
                        c = getParent().loadClass(name);
                    } else {
                        c = findSystemClass(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    c = findClass(name);

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }
}
